package com.test.webfluxhtml.common;

import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.net.URL;
import java.net.URLConnection;


public class ImageTool {

    public static FileDownLoadInfo downloadImageFromUrl(String imageUrl) throws Exception {
        FileDownLoadInfo fileDownLoadInfo = new FileDownLoadInfo();
        if (StringUtils.isBlank(imageUrl)) {
            return null;
        }
        URL url = new URL(imageUrl);
        URLConnection urlConnection = url.openConnection();
        fileDownLoadInfo.setFileContentType(urlConnection.getContentType());
        DataInputStream inputStream = new DataInputStream(urlConnection.getInputStream());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        byte[] content = outputStream.toByteArray();
        fileDownLoadInfo.setFileContentBytes(content);
        inputStream.close();
        outputStream.close();
        return fileDownLoadInfo;
    }
    /**
     * 通过前端上传的base64图片的字符串 获取图片的信息，无法得到图片的名称
     * @param base64ImageStr 前端上传的图片信息
     * @return 图片信息
     */
    public static Base64ImageInfo getBase64ImageInfoFromImageStr(String base64ImageStr)
    {
        if(StringUtils.isBlank(base64ImageStr))
        {
            return  null;
        }

        Base64ImageInfo info = new Base64ImageInfo();
        String[] infos = base64ImageStr.split(";");
        if(infos!=null && infos.length==2)
        {
            switch (infos[0].toLowerCase())
            {
                case "data:image/png":
                    info.setImageType("png");
                    break;
                case "data:image/jpeg":
                    info.setImageType("jpg");
                    break;
                case "data:image/bmp":
                    info.setImageType("bmp");
                    break;
                case "data:image/gif":
                    info.setImageType("gif");
                    break;
                default:
                    info.setMessage("不支持的图片类型");
                    return  info;
            }
            String[] dataStrs = infos[1].split(",");
            if(dataStrs!=null && dataStrs.length==2)
            {
                info.setImageEncodeType(dataStrs[0]);
                info.setImageData(dataStrs[1]);
            }else
            {
                return  null;
            }

        }else
        {
            return  null;
        }
        return  info;

    }
}
